/*
 * Copyright (c) 2018. paascloud.net All Rights Reserved.
 * 项目名称：paascloud快速搭建企业级分布式微服务平台
 * 类名称：TokenInterceptor.java
 * 创建人：刘兆明
 * 联系方式：paascloud.net@gmail.com
 * 开源地址: https://github.com/paascloud
 * 博客地址: http://blog.paascloud.net
 * 项目官网: http://paascloud.net
 */

package com.ruoyi.project.digital.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.ThreadLocalMap;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.digital.domain.dto.LoginWechatUser;
import com.ruoyi.project.digital.service.WechatUserTokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

/**
 * 频率限制拦截器
 * <p>
 * The class Token interceptor.
 *
 * @author kfc
 */
@Slf4j
@Component
public class WechatUserLoginInterceptor implements HandlerInterceptor {

    @Resource
    private ObjectMapper objectMapper;
    @Autowired
    private WechatUserTokenService wechatUserTokenService;

    /**
     * Pre handle boolean.
     *
     * @param request  the request
     * @param response the response
     * @param handler  the handler
     * @return the boolean
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String requestURI = request.getRequestURI();
        boolean isRpcRequest = requestURI.startsWith("/api/wu");
        if (isRpcRequest) {
            LoginWechatUser loginWechatUser = wechatUserTokenService.getLoginWechatUser(request);
            if (null == loginWechatUser){
                sendResponse(response);
                return false;
            }
            loginWechatUser.setURole(Constants.UROLE_WECHATUSER);
            wechatUserTokenService.verifyToken(loginWechatUser);
            ThreadLocalMap.put(Constants.WECHAT_AUTH,loginWechatUser);
        }
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        ThreadLocalMap.remove(Constants.WECHAT_AUTH);
    }


    private void sendResponse(HttpServletResponse response) {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        try (OutputStream out = response.getOutputStream();
             PrintWriter pw = new PrintWriter(new OutputStreamWriter(out, "utf-8"))) {
            // 返回json格式的提示
            pw.println(objectMapper.writeValueAsString( AjaxResult.error("请先登录后才能操作！")));
        } catch (IOException ex) {
            log.warn("", ex);
        }
    }
}
